package com.newenergy.wisehome.ui.fragment;


import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.Icon;
import com.newenergy.wisehome.data.bean.SecneGroup;
import com.newenergy.wisehome.data.bean.SecneMode;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.IconDao;
import com.newenergy.wisehome.data.ormlite.dao.SecneGroupDao;
import com.newenergy.wisehome.data.ormlite.dao.SecneModeDao;
import com.newenergy.wisehome.ui.adapter.GroupAdapter;
import com.newenergy.wisehome.ui.adapter.IconAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 *场景编辑
 *
 */
public class EditSceneFragment extends BaseFragment {

    private static String ARG_SECNEMODE="arg_secnemode";
    @BindView(R.id.tv_scene)
    TextView mTvScene;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.btn_select_icon)
    Button mBtnSelectIcon;
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;

    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;

    @BindView(R.id.rl_et)
    RelativeLayout mRlEt;

    @BindView(R.id.recyclerView_group)
    EasyRecyclerView mRecyclerViewGroup;

    private EasyRecyclerView mRecyclerView;
    private IconAdapter mIconAdapter;
    private GroupAdapter mGroupAdapter;
    private Icon mIcon;
    private PopupWindow mPopupWindow;
    private IconDao mIconDao;
    private Family mCurrFamily;
    private SecneMode mSecneMode;
    private List<BallLight> mSelectGroups = new ArrayList<>();
    private int confirmType = 1;
    private String mSecneName;


    public EditSceneFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_edit_scene;
    }

    public static ISupportFragment newInstance(SecneMode secneMode) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_SECNEMODE, secneMode);
        EditSceneFragment fragment = new EditSceneFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void init(View rootView) {
        initIconRecyclerView(getContext());
        initGroupRecyclerView(getContext());
        mIconDao = new IconDao(getContext());

    }

    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    private void refreshData() {
        mIconAdapter.refreshData(mIconDao.getIconsByType(2));
        mSecneMode = getArguments().getParcelable(ARG_SECNEMODE);
        mSecneName = mSecneMode.getName();
        mEtName.setText(mSecneName);
        mTvPage.setText(mSecneName);
//        mCurrFamily = mFamilyDao.getSelect();
        mCurrFamily=  AppManager.getInstance(getContext()).mCurrFamily;
        if (mCurrFamily != null) {
            BallLightDao ballLightDao = new BallLightDao(getContext());
            List<BallLight> groups = ballLightDao.getFamilyBallLights(mCurrFamily.getFamilyId(),1);

            mGroupAdapter.refreshData(groups);
        }
    }

    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_delete, R.id
            .btn_confirm, R.id
            .btn_cancel, R.id
            .btn_select_icon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_confirm:
                updateSecneName();
                break;
            case R.id.btn_cancel:
                doBack();
                break;
            case R.id.btn_select_icon:
                showPopupWindow();
                break;
            case R.id.btn_delete:
                String msg = getString(R.string.sure_delete) + mSecneMode.getName() + getString(R.string.this_scene);
                confirmType = 1;
                showConfirmDialog(msg);
                break;
        }
    }

    private void updateSecneName() {
        SecneModeDao secneModeDao = new SecneModeDao(getContext());
        String name = mEtName.getText().toString().trim();
        if (mSecneName.equals(name)){
            ToastUtil.myToast(getString(R.string.no_change_scene), true);
            return;
        }
        if (!checkSecneName(name)) return;
        mSecneMode.setName(name);

        secneModeDao.updateSecneMode(mSecneMode);
        mTvPage.setText(name);
        myToast(getString(R.string.modify_scene_success), false);

    }

    @Override
    protected void confirmOperation() {
        super.confirmOperation();
        if (confirmType == 1) deleteSecne();
    }

    private void deleteSecne() {
        SecneGroupDao secneGroupDao = new SecneGroupDao(getContext());
        SecneModeDao secneModeDao = new SecneModeDao(getContext());
        List<SecneGroup> secneGroups = secneGroupDao.getSecneGroups(mSecneMode.getId());
        secneGroupDao.delete(secneGroups);
        secneModeDao.delete(mSecneMode);
        myToast(getString(R.string.delete) + mSecneName + getString(R.string.success), false);
        doBack();

    }



    private void getSelectGroups() {
        mSelectGroups.clear();
        List<BallLight> allData = mGroupAdapter.getAllData();
        for (BallLight group : allData) {
            if (group.isChecked()) mSelectGroups.add(group);
        }
    }

    public void showPopupWindow() {
        int width = mRlEt.getWidth();
        mPopupWindow = new PopupWindow(mRecyclerView, width -
                dpToPx(20), ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable
                (Color.WHITE));
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAsDropDown(mRlEt, dpToPx(10), dpToPx(2));
    }

    private void initIconRecyclerView(Context context) {
        SecneModeDao secneModeDao = new SecneModeDao(getContext());
        mRecyclerView = (EasyRecyclerView) View.inflate(context, R
                .layout.popup_select_icon, null);
        mRecyclerView.setLayoutManager(new GridLayoutManager
                (context, 4));
        mRecyclerView.setBackgroundResource(R.drawable.bg_input);
        mIconAdapter = new IconAdapter(context);
        mRecyclerView.setAdapter(mIconAdapter);
        mIconAdapter.setOnItemClickListener(position -> {
            mIcon = mIconAdapter.getItem(position);
            mSecneMode.setIconName(mIcon.getIconName());
            myToast(getString(R.string.change_the_picture_successfully), false);
            secneModeDao.updateSecneMode(mSecneMode);
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
                mPopupWindow = null;
            }
        });
    }

    private void initGroupRecyclerView(Context context) {
        mRecyclerViewGroup.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerViewGroup.setBackgroundResource(R.drawable.bg_input);
        mGroupAdapter = new GroupAdapter(context);
        mRecyclerViewGroup.setAdapter(mGroupAdapter);
        mGroupAdapter.setOnItemClickListener(position -> {
            BallLight group = mGroupAdapter.getItem(position);
            group.setChecked(!group.isChecked());
            mGroupAdapter.notifyItemChanged(position);
        });
    }

}
